package com.jcli.novel_p;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 1.1.分页功能
 * 实现最大显示6页
 */
/*
参考代码
// 创建一个 JPanel 用于容纳页数按钮
JPanel pageButtonPanel = new JPanel();

// 在加载页面时，生成页数按钮并添加到 pageButtonPanel
private void loadPropertiesToTableModel() {
    // 清空表格模型
    tableModel.setRowCount(0);

    // 计算总页数
    int totalPages = (int) Math.ceil((double) properties.size() / ROWS_PER_PAGE);

    // 添加页数按钮之前，先清空页数按钮面板
    pageButtonPanel.removeAll();

    // 最多显示 6 个页数按钮
    int maxPageButtons = 6;

    // 计算起始和结束页数按钮
    int startPage = Math.max(1, currentPage - maxPageButtons / 2);
    int endPage = Math.min(totalPages, startPage + maxPageButtons - 1);

    // 添加页数按钮到页数按钮面板
    for (int i = startPage; i <= endPage; i++) {
        JButton pageButton = new JButton(Integer.toString(i));
        pageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 处理点击页数按钮的逻辑
                handlePageButtonClick(pageButton);
            }
        });
        pageButtonPanel.add(pageButton);
    }

    // 更新页数按钮面板
    pageButtonPanel.revalidate();
    pageButtonPanel.repaint();

    // ... 其他加载数据到表格的逻辑 ...
}



 */
public class WriteToPropertiesSwingWithPagination {
    private Properties properties;
    private int addedCount = 0;
    private JFrame frame;
    private DefaultTableModel tableModel;
    private JTable table;
    private JPanel pageButtonPanel;
    private int currentPage = 1;
    private static final int ROWS_PER_PAGE = 20;

    public WriteToPropertiesSwingWithPagination() {
        properties = new Properties();

        try (InputStream inputStream = new FileInputStream("src/main/resources/config.properties")) {
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建Swing界面
        frame = new JFrame("配置属性编辑器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 400);
        frame.setLayout(new BorderLayout());

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        tableModel.addColumn("键");
        tableModel.addColumn("值");
        table = new JTable(tableModel);

        // 创建页数按钮面板
        pageButtonPanel = new JPanel();

        // 添加表格到滚动窗格
        JScrollPane tableScrollPane = new JScrollPane(table);

        // 创建文本框和按钮
        JTextField keyTextField = new JTextField(20);
        JTextField valueTextField = new JTextField(20);
        JButton addButton = new JButton("添加属性");

        // 创建面板以容纳文本框和按钮
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("键:"));
        inputPanel.add(keyTextField);
        inputPanel.add(new JLabel("值:"));
        inputPanel.add(valueTextField);
        inputPanel.add(addButton);

        // 添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String key = keyTextField.getText().trim();
                String value = valueTextField.getText().trim();

                if (key.isEmpty() || value.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "键和值不能为空。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (properties.containsKey(key)) {
                    JOptionPane.showMessageDialog(frame, "键 '" + key + "' 已存在，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                } else if (properties.containsValue(value)) {
                    Set<String> keys = properties.stringPropertyNames();
                    boolean valueExistsWithDifferentKey = false;

                    for (String existingKey : keys) {
                        if (properties.getProperty(existingKey).equals(value) && !existingKey.equals(key)) {
                            valueExistsWithDifferentKey = true;
                            break;
                        }
                    }

                    if (valueExistsWithDifferentKey) {
                        int option = JOptionPane.showConfirmDialog(frame, "值 '" + value + "' 已存在，但键不同。是否录入已有的键值对？", "确认", JOptionPane.YES_NO_OPTION);
                        if (option == JOptionPane.YES_OPTION) {
                            properties.setProperty(key, value);
                            addedCount++;
                            JOptionPane.showMessageDialog(frame, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(frame, "已跳过键 '" + key + "' 的录入。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(frame, "值 '" + value + "' 已存在，但键相同，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                    }
                } else {
                    properties.setProperty(key, value);
                    addedCount++;
                    JOptionPane.showMessageDialog(frame, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                }

                // 清空文本框
                keyTextField.setText("");
                valueTextField.setText("");

                // 将属性加载到表格模型中并刷新表格
                loadPropertiesToTableModel();
            }
        });

        // 添加组件到界面
        frame.add(inputPanel, BorderLayout.NORTH);
        frame.add(tableScrollPane, BorderLayout.CENTER);
        frame.add(pageButtonPanel, BorderLayout.SOUTH);

        // 显示初始的所有键值对
        loadPropertiesToTableModel();
        updatePageButtons();

        frame.setVisible(true);
    }

    // 在加载页面时，生成页数按钮并添加到 pageButtonPanel
    private void updatePageButtons() {
        // 清空页数按钮面板
        pageButtonPanel.removeAll();

        // 计算总页数
        int totalPages = (int) Math.ceil((double) properties.size() / ROWS_PER_PAGE);

        // 最多显示 6 个页数按钮
        int maxPageButtons = 6;

        // 计算起始和结束页数按钮
        int startPage = Math.max(1, currentPage - maxPageButtons / 2);
        int endPage = Math.min(totalPages, startPage + maxPageButtons - 1);

        // 添加页数按钮到页数按钮面板
        for (int i = startPage; i <= endPage; i++) {
            JButton pageButton = new JButton(Integer.toString(i));
            pageButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 处理点击页数按钮的逻辑
                    handlePageButtonClick(pageButton);
                }
            });
            pageButtonPanel.add(pageButton);
        }

        // 更新页数按钮面板
        pageButtonPanel.revalidate();
        pageButtonPanel.repaint();
    }

    // 处理页数按钮点击事件
    private void handlePageButtonClick(JButton pageButton) {
        int newPage = Integer.parseInt(pageButton.getText());
        if (newPage != currentPage) {
            currentPage = newPage;
            loadPropertiesToTableModel();
            updatePageButtons();
        }
    }

    // 加载属性到表格模型中
    private void loadPropertiesToTableModel() {
        // 清空表格模型
        tableModel.setRowCount(0);

        // 计算起始索引和结束索引
        int startIndex = (currentPage - 1) * ROWS_PER_PAGE;
        int endIndex = Math.min(properties.size(), startIndex + ROWS_PER_PAGE);

        int row = 0;
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            if (row >= startIndex && row < endIndex) {
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();
                tableModel.addRow(new Object[]{key, value});
            }
            row++;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new WriteToPropertiesSwingWithPagination();
            }
        });
    }
}
